//规则, 组件名字驼峰, 元素标签中划线分割, 两者映射缺一不可.
angular.module("app").component("winitDepartmentNeed", {
    templateUrl: getTemplateUrl("matrix/component/tpl/winitDepartmentNeed.html"),
    bindings: {
        userList: "<",
        need: "<",
        lowerValue: "=",
        showBtn: "<",
        saveNeed: "&",
        deptReadOnly:"<"
    },
    controller: function (
        $http,
        $rootScope,
        $scope,
        $stateParams,
        $element,
        $attrs,
        $timeout,
        lodash
    ) {
        var ctrl = this;
        $scope.info = {
            need: {
                reduceLoss: 0, profit: 0, cycle: 0, pages: [],
                lossPrevent: {isChecked: null}, mayProfit: {isChecked: null}, saveCost: {isChecked: null}
            }, weekArray: [], crtItemDate: ""
        };
        ctrl.info = {
            objectives: null,
            customer: {},
            selCustomer: {},
            selDepartment: {},
            isEnded: false
        };
        ctrl.departmentSaveNeed = function () {
            ctrl.saveNeed();
        };

        $scope.isVisible=true;
        $scope.isCommited = false;//是否完成部门评审
        $scope.isdepartAble = false;
        ctrl.departments = {isEnded: false}
        $scope.Opendepartment = true;

        $scope.isAdmin = $rootScope.isUserCanOperateByRole();
        // 给部门评定
        $scope.isMaster = $rootScope.isUserCanOperateByRole("dept_charger") //是否具有master权限
        //处理角色权限
        $scope.duleRole = function () {
            //需求的状态是否正确
            $scope.info.needStatus = ctrl.need.status == "NO_ACCEPT" ? true : false;
            if ($scope.info.needStatus && $scope.isMaster) {
                $scope.isCommited = false;
            } else if ($scope.info.needStatus && !$scope.isMaster) {
                $scope.isCommited = true;
            } else if (!$scope.info.needStatus && $scope.isMaster) {
                $scope.isCommited = true;
            } else {
                $scope.isCommited = true;
            }
            //页面的组件控制
            if ($scope.isMaster && $scope.info.needStatus) {
                $scope.isdepartAble = false;
            } else {
                $scope.isdepartAble = true;
            }
        }
        //确定部门评审是否已经完成
        $scope.commit = function() {
          var filter = config_need_status.filter(function(a) {
            return a.key == ctrl.need.status;
          });
          if (filter[0]) {
            if (filter[0].index >= 2) {
              $scope.isCommited = true;
            } else {
              if ($scope.isMaster) {
                $scope.isCommited = false;
              } else {
                $scope.isCommited = true;
                $scope.isVisible = false;
              }
              if ($scope.isAdmin) {
                $scope.isCommited = true;
                $scope.isVisible = true;
              }
            }
          }
        };

        //获取优先级的字符串
        $scope.getDeptPriorityStr = function() {
          var value = ctrl.need.deptPriority;
          if (value >= 4) ctrl.need.deptPriorityStr = "高";
          if (value >= 3) ctrl.need.deptPriorityStr = "较高";
          if (value >= 2) ctrl.need.deptPriorityStr = "中";
          if (value >= 1) ctrl.need.deptPriorityStr = "较低";
          ctrl.need.deptPriorityStr = "低";
        };

        //获取需求目的的字符串
        $scope.getPurposeStr = function() {
            var purpose = []
            if (ctrl.need.purpose && ctrl.need.purpose != "") {
                purpose = ctrl.need.purpose.split(",").filter(function (a) {
                    return a != ""
                })
                ctrl.need.purposeStr = ""
                $scope.purposes = []
                ctrl.need.sltObj=[]
                purpose.forEach(function (a) {
                    config_need_objectives.forEach(function (b) {
                        if (a == b.key) {
                            $scope.purposes.push(b)
                            b.check = true
                            ctrl.need.sltObj.push(b)
                        }
                    })
                })
                $scope.purposes.forEach(function (a) {
                    var otherPurposes = ""
                    if(a.key=="6"){
                        otherPurposes=a.value+":"+ctrl.need.otherPurposes
                        ctrl.need.purposeStr+=otherPurposes+"/"
                    }else {
                        ctrl.need.purposeStr += (a.value + "/")
                    }
                })
                ctrl.need.purposeStr = ctrl.need.purposeStr.substring(0, ctrl.need.purposeStr.lastIndexOf('/'))
            }
        }
        //节省成本的添加字段
        $scope.updateSaveCostContent = function() {
            if (ctrl.need.expectLowerCostList && ctrl.need.expectLowerCostList.length > 0) {
             ctrl.need.expectLowerCostList.forEach(function(a) {
              if (a.role == "customer") {
                a.roleName = "客服专员";
              } else if (a.role == "houser") {
                a.roleName = "仓库专员";
              } else if (a.role == "pdm") {
                a.roleName = "PDM";
              } else if (a.role == "dev") {
                a.roleName = "开发";
              } else if (a.role == "qa") {
                a.roleName = "测试";
              } else if (a.role == "ops") {
                a.roleName = "运维";
              } else if (a.role == "pd") {
                a.roleName = "产品";
              } else if (a.role == "manager") {
                a.roleName = "经理";
              } else {
                a.roleName = "";
              }
              if (a.cycle == "d") {
                a.cycleName = "天";
              } else if (a.cycle == "w") {
                a.cycleName = "周";
              } else if ((a.cycle = "m")) {
                a.cycleName = "月";
              } else a.cycleName = "";
            });
          }
        };

        //初始化数据
        $scope.initialDatas=function(){
            $scope.currentReduceLoss = ctrl.need.reduceLoss?ctrl.need.reduceLoss:""
            $scope.currentProfit = ctrl.need.profit?ctrl.need.profit:"";
            if (ctrl.need.saveCost) {
                if (ctrl.need.saveCost.isChecked) {
                    if (ctrl.need.expectLowerCostList && ctrl.need.expectLowerCostList == "") {
                        $scope.temp = [{role: "customer", userNum: "0", cycle: "d", hours: "0"}]
                    } else if (ctrl.need.expectLowerCostList && ctrl.need.expectLowerCostList.length > 0) {
                        $scope.temp = ctrl.need.expectLowerCostList
                    } else if (ctrl.need.expectLowerCostList && ctrl.need.expectLowerCostList.length == 0) {
                        $scope.temp = [{role: "customer", userNum: "0", cycle: "d", hours: "0"}]
                    }
                }
            }
            console.log("temp"+JSON.stringify($scope.temp))

        }
        //获取需求目的数组
        $scope.getDeptPriorityStr()
        $scope.duleRole();
        $scope.commit();
        $scope.getPurposeStr()
        $scope.updateSaveCostContent()
        $scope.initialDatas()
        ctrl.$onChanges = function () {
            $scope.info.need = ctrl.need;
            setExpectedSchedule(ctrl.need);
            getDataType(ctrl.showBtn);
            $scope.duleRole();
            $scope.commit();
            $scope.getLowerValue();
            $scope.getDeptPriorityStr();
            $scope.getPurposeStr()
            $scope.updateSaveCostContent()
            $scope.initialDatas()

        };

        // 切换switch
        $scope.changeSwitch = function (deptTrain) {
            $scope.info.need.deptTrain = deptTrain;
        };

        $scope.addLowerCost = function () {
            var obj = {role: "customer", userNum: 0, cycle: "d", hours: 0};
            if (!ctrl.need.expectLowerCostList) {
                ctrl.need.expectLowerCostList = [];
            }
            ctrl.need.expectLowerCostList.push(obj);
        };

        $scope.delLowerCost = function (info) {
            console.log(ctrl.need.expectLowerCostList);
            ctrl.need.expectLowerCostList.pop(info);
            console.log(ctrl.need.expectLowerCostList);
            info.isDel = true;
        };

        //计算参考价值
        // $scope.info.lowerValue = 0;
        ctrl.lowerValue = 0;
        $scope.getLowerValue = function () {
            $scope.info.lowerValue = 0;
            if ($scope.info.need.expectLowerCostList) {
                angular.forEach($scope.info.need.expectLowerCostList, function (info) {
                    if (info.isDel != undefined && info.isDel == true) {
                        return false;
                    }
                    switch (info.cycle) {
                        case "d":
                            $scope.info.lowerValue =
                                $scope.info.lowerValue + info.userNum * info.hours * 20 * 12;
                            break;
                        case "w":
                            $scope.info.lowerValue =
                                $scope.info.lowerValue + info.userNum * info.hours * 4 * 12;
                            break;
                        case "m":
                            $scope.info.lowerValue =
                                $scope.info.lowerValue + info.userNum * info.hours * 12;
                            break;
                    }
                });
            }
            $scope.info.lowerValue = $scope.info.lowerValue / (20 * 8);
            if ($scope.info.need.reduceLoss) {
                $scope.info.lowerValue += parseInt($scope.info.need.reduceLoss);
            }
            if ($scope.info.need.profit) {
                $scope.info.lowerValue += parseInt($scope.info.need.profit);
            }
            ctrl.lowerValue = $scope.info.lowerValue;
            ctrl.need.deptRefValue=$scope.info.lowerValue
            return $scope.info.lowerValue;
        };

        // 设置排期时间
        function setExpectedSchedule(need) {
            $scope.info.weekArray = getWeekArray();
            var weekItem = lodash.findWhere($scope.info.weekArray, {
                ms: need.expectedSchedule
            });
            $scope.info.crtItemDate = weekItem;
        }

        // 设置选中时间
        $scope.selectDateItem = function (data) {
            ctrl.need.Schedule = data.ms || "";
        };

        //预防损失

        $scope.lossPrevent = function(value) {
            if(!value.isChecked)
                ctrl.need.reduceLoss=0
            else
                ctrl.need.reduceLoss= $scope.currentReduceLoss
        };
        //可能盈利

        console.log("11111111"+ctrl.need.profit)
        $scope.mayProfit = function(value) {
            if(!value.isChecked)
                ctrl.need.profit=0
            else
                ctrl.need.profit= $scope.currentProfit
        };

        //监听预防损失
        $scope.$watch("$ctrl.need.reduceLoss",function () {
            if(ctrl.need.reduceLoss>0){
                ctrl.need.lossPrevent.isChecked=true
            }
        })

        //监听可能盈利
        $scope.$watch("$ctrl.need.profit",function () {
            if(ctrl.need.profit>0){
                ctrl.need.mayProfit.isChecked=true
            }
        })

        $scope.saveCostClick=function (value) {
            if(value.isChecked){
                if($scope.temp==""||!$scope.temp){
                ctrl.need.expectLowerCostList=[{role: "customer", userNum: "0", cycle: "d", hours: "0"}]
                }else {
                    ctrl.need.expectLowerCostList = $scope.temp
                }
            }else{
                ctrl.need.expectLowerCostList=""
            }
        }

        // 保存选中的需求目数据 选择目的后促发相应动作
        $scope.selecObjective = function(obj) {
          ctrl.need.sltObj = [];
          if (obj) {
            obj.check = !obj.check;
          }

          angular.forEach(ctrl.info.objectives, function(objective) {
            if (objective.check) {
              ctrl.need.sltObj.push(objective);
            }
          });

          //每次刷新赋值
          ctrl.need.lossPrevent.isChecked = false;
          ctrl.need.mayProfit.isChecked = false;
          ctrl.need.saveCost.isChecked = false;
          $scope.lossAble = false;
          $scope.saveAble = false;
          $scope.profitAble = false;
          //处理逻辑判断
          ctrl.need.sltObj.forEach(function(objective) {
            var key = objective.key;
            if (key == "5" || key == "7") {
              ctrl.need.lossPrevent.isChecked = true;
              $scope.lossAble = true;
            }
            if (key == "3" || key == "2") {
              ctrl.need.saveCost.isChecked = true;
              $scope.saveAble = true;
            }
            if (key == "4") {
              ctrl.need.mayProfit.isChecked = true;
              $scope.profitAble = true;
            }
          });


          //处理数据
          if (ctrl.need.expectLowerCostList && ctrl.need.expectLowerCostList == "") {
            $scope.temp = [{ role: "customer", userNum: "0", cycle: "d", hours: "0" }];
          } else if (ctrl.need.expectLowerCostList && ctrl.need.expectLowerCostList.length > 0) {
            $scope.temp = ctrl.need.expectLowerCostList;
          } else if (ctrl.need.expectLowerCostList && ctrl.need.expectLowerCostList.length == 0) {
            $scope.temp = [{ role: "customer", userNum: "0", cycle: "d", hours: "0" }];
          }

          if (ctrl.need.saveCost.isChecked) {
            if (!ctrl.need.expectLowerCostList || ctrl.need.expectLowerCostList.length == 0) {
              ctrl.need.expectLowerCostList = [{ role: "customer", userNum: "0", cycle: "d", hours: "0" }];
            } else {
              ctrl.need.expectLowerCostList = $scope.temp;
            }
          } else {
            ctrl.need.expectLowerCostList = "";
          }

          if (!ctrl.need.mayProfit.isChecked) {
            ctrl.need.profit = 0;
          }
          if (!ctrl.need.lossPrevent.isChecked) {
            ctrl.need.reduceLoss = 0;
          }

          ctrl.otherS = lodash.findWhere(ctrl.need.sltObj, {
            value: "其他"
          });

          if (ctrl.otherS) {
            ctrl.need.showObjItem = true;
          } else {
            ctrl.need.showObjItem = false;
            ctrl.need.sltItemValue = "";
          }
        };
        // 获取数据类型（需求来源，需求类型，需求目的）
        function getDataType(showBtn) {
            if ($stateParams.type) {
                angular.forEach(config_need_objectives, function (obj) {
                    obj.check = false;
                });
            }


            ctrl.info.objectives = config_need_objectives;
            angular.forEach(ctrl.info.objectives, function (obj) {
                var otherS = lodash.findWhere(ctrl.need.purpose, obj.key);
                if (otherS) {
                    obj.check = true;
                    if (obj.key == 6) {
                        ctrl.need.showObjItem = true;
                    }
                }
            });
        }



        ctrl.info.isEnded=false
        //部门领导人准备提交
        $scope.prepareCommit = function (value) {
            console.log("部门领导人准备提交" + JSON.stringify(value))
            ctrl.info.isEnded = value
            $scope.isdepartAble = value
        }

        //评审完成保存数据
        $scope.departmentAffirm = function () {


            console.log("评审完成------");

            if(!ctrl.need.sltObj){
                ctrl.info.isEnded = false
                $scope.isdepartAble = false
                $rootScope.toasterWarningInfo("需求目的不能为空");
                return
            }else {
                if(ctrl.need.sltObj.length==0){
                    ctrl.info.isEnded = false
                    $scope.isdepartAble = false
                    $rootScope.toasterWarningInfo("需求目的不能为空");
                    return
                }
            }

            if (ctrl.need.lossPrevent.isChecked) {
                if (ctrl.need.reduceLoss == 0) {
                    ctrl.info.isEnded = false
                    $scope.isdepartAble = false
                    $rootScope.toasterWarningInfo("预防损失不能为0");
                    return
                }
            }
            if (ctrl.need.mayProfit.isChecked) {
                if (ctrl.need.profit == 0) {
                    ctrl.info.isEnded = false
                    $scope.isdepartAble = false
                    $rootScope.toasterWarningInfo("盈利不能为0");
                    return
                }
            }
            if (ctrl.need.saveCost.isChecked) {
                var passed = false;
                var expectLowerCostList = ctrl.need.expectLowerCostList;
                if (expectLowerCostList.length >= 1) {
                    expectLowerCostList.forEach(function (a) {
                        var userNum = a.userNum;
                        var hours = a.hours;
                        if (userNum == 0 || hours == 0) {
                            ctrl.info.isEnded = false;
                            $scope.isdepartAble = false;
                            passed = false;
                        } else {
                            passed = true;
                        }
                    });
                }
                if (!passed) {
                    $rootScope.toasterWarningInfo("节约成本的内容里不能有0");
                    return;
                }
            }


            var confirmParams = {
                "titleData": "提示",
                "bodyData": "确定部门评审结束"
            };

            $rootScope.confirmWindow(confirmParams, function (data) {
                if (data) {
                    $scope.isdepartAble = true
                    $scope.isCommited = true
                    ctrl.need.status = "DEPARTMENT_REVIEW"
                    ctrl.info.isEnded = true
                    ctrl.saveNeed()
                }
            });

        }

        //可编辑按钮切换
        $scope.isDisabled = false;
        $scope.deptEdit=function () {
            $scope.isDisabled = true;
            $scope.isCommited=false
            ctrl.info.isEnded = false;
            $scope.isdepartAble = false;
            $timeout(function () {
                $scope.isDisabled = false;
            },1000)
        }
    }
});
